package org.jeecg.modules.htxincailiao.cart.controller;

import java.util.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.collect.Maps;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.htxincailiao.account.entity.HTPlatformUser;
import org.jeecg.modules.htxincailiao.account.service.IHTAccountService;
import org.jeecg.modules.htxincailiao.cart.domain.vo.HTCartSessionVO;
import org.jeecg.modules.htxincailiao.cart.domain.vo.HTCartUpdateVO;
import org.jeecg.modules.htxincailiao.cart.domain.vo.HTCartVO;
import org.jeecg.modules.htxincailiao.order.domain.vo.HTOrderVO;
import org.jeecg.modules.htxincailiao.order.constant.HTOrderInfoTypeEnum;
import org.jeecg.modules.htxincailiao.cart.common.HTCartConfig;
import org.jeecg.modules.htxincailiao.order.domain.bo.HTOrderInfoBO;
import org.jeecg.modules.htxincailiao.cart.domain.dto.HTCartQueryDTO;
import org.jeecg.modules.htxincailiao.cart.entity.HTCart;
import org.jeecg.modules.htxincailiao.cart.service.IHTCartService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.modules.htxincailiao.order.service.IHTOrderService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

import static org.jeecg.modules.htxincailiao.order.constant.HTOrderInfoTypeEnum.CART_INFO;

/**
 * @Description: ht_cart
 * @Author: jeecg-boot
 * @Date:   2021-06-07
 * @Version: V1.0
 */
@Api(tags="ht_cart")
@RestController
@RequestMapping("/cart/hTCart")
@Slf4j
public class HTCartController extends JeecgController<HTCart, IHTCartService> {
	@Resource
	private IHTCartService cartService;

	@Resource
	private IHTAccountService accountService;

	@Resource
	private IHTOrderService orderService;


	/**
	 * 购物车列表
	 *
	 * @param @param  model
	 * @param @return
	 * @param @throws JsonGenerationException
	 * @param @throws JsonMappingException
	 * @param @throws Exception    设定文件
	 * @return Map<String, String>    返回类型
	 * @throws
	 * @Title: cartz
	 * @Description: 购物车列表 （按店铺整合）
	 */
	@PostMapping(value = "/cartInfo")
	public Result<?> cartInfo(HttpServletRequest request, HttpSession session, @RequestBody HTCartQueryDTO query) {
		Result<JSONObject> result = new Result<>();
		HTOrderVO cartInfo = null;

		//判断是否登录,登录存表,不登录将信息存入session
		String token = request.getHeader(CommonConstant.X_ACCESS_TOKEN);
		//若登录,查表 subject.isAuthenticated()
		if (oConvertUtils.isNotEmpty(token)){
			String username = JwtUtil.getUsername(token);
//			System.out.printf("\n\n\ncart info username %s \n\n\n", JSONObject.toJSONString(username));
			HTPlatformUser user = accountService.queryFrontendUserByUsername(username);
			HTOrderInfoBO bo = new HTOrderInfoBO();
			bo.setBuyerId(user.getId());
			bo.setOrderInfoType(CART_INFO);

			cartInfo = orderService.getOrderInfoByOrderInfoType(bo);
		}
		else {
			result.error500("未登录");
		}

		JSONObject obj = new JSONObject(  );
		obj.put("cartInfo", cartInfo);
		result.setResult(obj);

		return result;
	}


	/**
	 * 分页列表查询
	 *
	 * @param hTCart
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "ht_cart-分页列表查询")
	@ApiOperation(value="ht_cart-分页列表查询", notes="ht_cart-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(HTCart hTCart,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<HTCart> queryWrapper = QueryGenerator.initQueryWrapper(hTCart, req.getParameterMap());
		Page<HTCart> page = new Page<HTCart>(pageNo, pageSize);
		IPage<HTCart> pageList = cartService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	/**
	 *   添加
	 *
	 * @param hTCart
	 * @return
	 */
	@AutoLog(value = "ht_cart-添加")
	@ApiOperation(value="ht_cart-添加", notes="ht_cart-添加")
	@PostMapping(value = "/add")
	public Result<?> add(HttpServletRequest request, @RequestBody HTCart hTCart) {
		String token = request.getHeader(CommonConstant.X_ACCESS_TOKEN);
		String username = JwtUtil.getUsername(token);

		HTPlatformUser user = accountService.queryFrontendUserByUsername(username);

		hTCart.setBuyerId(user.getId());

		HTCart storedShopCart = null;
		if (oConvertUtils.isNotEmpty(hTCart.getGoodsId())){
			storedShopCart = cartService.getByGoodsId(hTCart.getGoodsId());
		}

		if (oConvertUtils.isNotEmpty(hTCart.getLibraryId())){
			storedShopCart = cartService.getByLibraryId(hTCart.getLibraryId());
		}

		if (oConvertUtils.isNotEmpty(hTCart.getReportId())){
			storedShopCart = cartService.getByReportId(hTCart.getReportId());
		}

		if (oConvertUtils.isNotEmpty(storedShopCart)) {
			Integer quantity = storedShopCart.getQuantity() + hTCart.getQuantity();
			storedShopCart.setQuantity(quantity);

			edit(storedShopCart);
		}
		else {
			cartService.save(hTCart);
		}

		return Result.OK("添加成功！");
	}

	/**
	 *  批量更新
	 *
	 * @param orderProductItems
	 * @return
	 */
	@AutoLog(value = "ht_cart-批量删除")
	@ApiOperation(value="ht_cart-批量删除", notes="ht_cart-批量删除")
	@PostMapping(value = "/updateBatch")
	public Result<?> updateBatch(@RequestBody String orderProductItems) {
		Map cartItemsMap = JSONObject.parseObject(orderProductItems, Map.class);
		String cartListString = cartItemsMap.get("orderProductItems").toString();
		JSONArray cartArray = JSONObject.parseArray(cartListString);
		List<HTCartVO> cartVOList = cartArray.toJavaList(HTCartVO.class);

		HTCartUpdateVO updateVO = this.cartService.updateBatch(cartVOList);
		if (updateVO.isSucceed()) {
			Result<JSONObject> result = new Result<>();
			JSONObject obj = new JSONObject(  );
			obj.put("cartUpdateInfo", updateVO);
			result.setResult(obj);
			result.setMessage("更新成功");

			return result;
		}
		else  {
			return Result.error("网络出错，请到户外走一走");
		}
	}



	/**
	 *  编辑
	 *
	 * @param hTCart
	 * @return
	 */
	@AutoLog(value = "ht_cart-编辑")
	@ApiOperation(value="ht_cart-编辑", notes="ht_cart-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody HTCart hTCart) {
		cartService.updateById(hTCart);
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "ht_cart-通过id删除")
	@ApiOperation(value="ht_cart-通过id删除", notes="ht_cart-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		cartService.removeById(id);
		return Result.OK("删除成功!");
	}


	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "ht_cart-批量删除")
	@ApiOperation(value="ht_cart-批量删除", notes="ht_cart-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		log.info("\n\n\t\t ids = {}  \n\n" , ids);
		this.cartService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	@DeleteMapping(value = "deleteAll")
	public Map<String,Object> deleteAll(HttpServletRequest request, HttpSession session){
		Map<String, Object> map = Maps.newHashMap();
		String token = request.getHeader(CommonConstant.X_ACCESS_TOKEN);
		String username = JwtUtil.getUsername(token);

		HTPlatformUser user = accountService.queryFrontendUserByUsername(username);

		if (oConvertUtils.isNotEmpty(user) && oConvertUtils.isNotEmpty(user.getId())){
			//删除session购物车
			//从session中获取购物车数据
			HTCartSessionVO cartVo = (HTCartSessionVO) session.getAttribute(HTCartConfig.CART_SESSION_KEY);
			//通过物品的id和规格的id删除session中数据
//            cartVo.delete(cart.getGoodsId(), cart.getSpecId());
			cartVo = new HTCartSessionVO();
			map.put("success", true);
			return map;
		}else {
			LambdaQueryWrapper<HTCart> queryWrapper=new LambdaQueryWrapper<>();
			queryWrapper.eq(HTCart::getBuyerId, user.getId());
			cartService.remove(queryWrapper);
			map.put("success", true);
			return map;
		}
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "ht_cart-通过id查询")
	@ApiOperation(value="ht_cart-通过id查询", notes="ht_cart-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		HTCart hTCart = cartService.getById(id);
		if(hTCart ==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(hTCart);
	}

	/**
	 * 导出excel
	 *
	 * @param request
	 * @param hTCart
	 */
	@RequestMapping(value = "/exportXls")
	public ModelAndView exportXls(HttpServletRequest request, HTCart hTCart) {
		return super.exportXls(request, hTCart, HTCart.class, "ht_cart");
	}

	/**
	 * 通过excel导入数据
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/importExcel", method = RequestMethod.POST)
	public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
		return super.importExcel(request, response, HTCart.class);
	}

}
